<template>
  <div>
    <p style="display: flex">
      <el-button type="info" icon="el-icon-refresh" size="mini"
                 @click="list()">刷新
      </el-button>
      <el-button type="info" size="mini"
                 @click="addCourse()">添加
      </el-button>
      <el-button type="info" icon="el-icon-refresh" size="mini"
                 @click="list()">刷新
      </el-button>
    </p>
    <p style="display: flex">
      <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pageInfo.size"
          :current-page="pageInfo.page"
          @current-change="list"
          :total="pageInfo.total">
      </el-pagination>
      <el-select v-model="pageInfo.size" placeholder="请选择"
                 @change="list(1)">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"

            :value="item.value">
        </el-option>
      </el-select>
    </p>
    <div>
      <el-dialog title="添加课程" :visible.sync="dialogVisible">

        <el-form :model="form">

          <el-form-item label="分类" :label-width="formLabelWidth">
            <el-tree
                :data="categories"
                show-checkbox
                node-key="id"
                ref="tree"
                highlight-current
                :props="defaultProps">
            </el-tree>
          </el-form-item>

          <el-form-item label="名称" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="讲师" :label-width="formLabelWidth">
            <el-select v-model="form.teacherId" placeholder="请选择">
              <el-option
                  v-for="item in teacherList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="概述" :label-width="formLabelWidth">
            <el-input v-model="form.summary" autocomplete="off"></el-input>
          </el-form-item>


          <el-form-item label="时长" :label-width="formLabelWidth">
            <el-input v-model="form.time" autocomplete="off"></el-input>
          </el-form-item>


          <el-form-item label="价格（元）" :label-width="formLabelWidth">
            <el-input v-model="form.price" autocomplete="off"></el-input>
          </el-form-item>


          <el-form-item label="封面" :label-width="formLabelWidth">
            <el-upload
                class="upload-course-image"
                action="http://localhost:9000/file/admin/upload"
                :on-success="uploadImageSuccess"
                :data="uploadData"
                show-file-list="false">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>


          <el-form-item label="级别" :label-width="formLabelWidth">
            <el-select v-model="form.level" placeholder="请选择">
              <el-option
                  v-for="item in COURSE_LEVEL"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="收费" :label-width="formLabelWidth">
            <el-select v-model="form.charge" placeholder="请选择">
              <el-option
                  v-for="item in COURSE_CHARGE"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option
                  v-for="item in COURSE_STATUS"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="报名数" :label-width="formLabelWidth">
            <el-input v-model="form.enroll" autocomplete="off"></el-input>
          </el-form-item>


          <el-form-item label="顺序" :label-width="formLabelWidth">
            <el-input v-model="form.sort" autocomplete="off"></el-input>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCancel">取 消</el-button>
          <el-button type="primary" @click="saveCourse">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="课程内容" :visible.sync="courseContentDialog">

        <el-form :model="form">
          <markdown-editor ref-id="courseContent" v-model="courseContent"/>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button>取 消</el-button>
          <el-button type="primary" @click="saveCourseContent()">确 定</el-button>
        </div>
      </el-dialog>
      <div style="display: flex">
        <course-item v-for="(course,index) in pageInfo.list" :course-model="course" @del="del" @edit="edit"
                     :key="index" @goChapter="goChapter"
                     @courseContent="editCourseContent"/>
      </div>
    </div>

  </div>
</template>

<script>
import {list, deleteCourse, saveCourse, categoryList, getCourseContent, saveCourseContent} from "@/network/course";
import {Confirm} from '@/assets/js/confirm'
import {Validator} from "@/assets/js/validator";
import CourseItem from "@/views/admin/course/CourseItem";
import {allTeacher} from "@/network/teacher";
import MyMarkdown from "@/components/common/markdown/MyMarkdown";
import {allCategory} from "@/network/category";

export default {
  name: "course",
  components: {MyMarkdown, CourseItem},
  mounted() {
    this.list(1)
    this.allCategories();
  },
  data() {
    return {
      COURSE_LEVEL: COURSE_LEVEL,
      COURSE_CHARGE: COURSE_CHARGE,
      COURSE_STATUS: COURSE_STATUS,
      pageInfo: {
        page: 1,
        size: 1,
        list: [],
        total: 0,
      }, options: [
        {
          value: 1,
          label: 1
        },
        {
          value: 5,
          label: 5
        },
        {
          value: 10,
          label: 10
        },
        {
          value: 50,
          label: 50
        },],
      dialogVisible: false,
      courseContentDialog: false,
      form: {},
      formLabelWidth: '120px',
      categories: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      courseContent: '',
      courseId: '',
      teacherList: [],
      uploadData: {
        use: FILE_USE.COURSE.key
      }
    }
  },
  methods: {
    list(page) {
      if (page === null || page === undefined) {
        page = this.pageInfo.page
      }
      let _this = this;
      list(page, _this.pageInfo.size).then(res => {
        _this.pageInfo = res.data
      })
    },
    saveCourse() {
      let _this = this;
      // 保存校验
      if (1 !== 1
          || !Validator.require(_this.form.name, "名称")
          || !Validator.length(_this.form.name, "名称", 1, 50)
          || !Validator.length(_this.form.summary, "概述", 1, 2000)
          || !Validator.length(_this.form.image, "封面", 1, 100)
      ) {
        return;
      }
      _this.form.categoryModelList = this.$refs.tree.getCheckedNodes()
      saveCourse(_this.form).then(res => {
        _this.$message.success("保存成功");
        _this.form = {}
        _this.dialogVisible = false;
        _this.list()
      })
    },
    edit(row) {
      console.log(row);
      let _this = this;
      _this.loadTeacherList();
      _this.form = Object.assign({}, row)
      _this.dialogVisible = true;
      categoryList(row.id).then(res => {
        let checked = [];
        for (let i = 0; i < res.data.length; i++) {
          checked.push(res.data[i].categoryId);
        }
        _this.$refs.tree.setCheckedKeys(checked);
      })
    },
    del(row) {
      let _this = this;
      Confirm.show('此操作将永久删除该文件, 是否继续?', function () {
        deleteCourse(row.id).then(res => {
          _this.list();
          _this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      })
    },
    dialogCancel() {
      let _this = this;
      _this.form = {};
      _this.dialogVisible = false;
    },
    goChapter(course) {
      let _this = this;
      SessionStorage.set("course", course);
      this.$router.push("/admin/chapter")
    },
    allCategories() {
      let _this = this;
      _this.categories = [];
      allCategory().then(res => {
        console.log('categories')
        console.log(res)
        for (let i = 0; i < res.data.length; i++) {
          let c = res.data[i];
          if (c.parent === '00000000') {
            _this.categories.push(c);
            c.children = [];
            for (let j = 0; j < res.data.length; j++) {
              if (res.data[j].parent == c.id) {
                c.children.push(res.data[j]);
              }
            }
          }
        }
      })
    },
    addCourse() {
      let _this = this;
      _this.loadTeacherList();
      _this.form = {}
      _this.dialogVisible = true;
      _this.$refs.tree.setCheckedKeys([]);

    },
    editCourseContent(row) {
      let _this = this;
      _this.courseId = row.id;
      _this.courseContent = '';
      getCourseContent(row.id).then(res => {
        console.log(res)
        _this.courseContent = res.data.content;
      })
      _this.courseContentDialog = true;
    },
    saveCourseContent() {
      let _this = this;
      saveCourseContent({id: _this.courseId, content: _this.courseContent}).then(res => {
        _this.courseId = '';
        _this.courseContent = '';
        _this.courseContentDialog = false;
      })

    },
    loadTeacherList() {
      let _this = this;
      allTeacher().then(res => {
        _this.teacherList = res.data;
      })
    },
    uploadImageSuccess(res, file) {
      let _this = this;
      _this.form.image = res.data;
    }
  }
}
</script>

<style scoped>

</style>
